#!/usr/bin/env python

import os
import logging
import urllib

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

from idigi import Sample, iDigiClient
from config import Config

USERNAME = Config.USERNAME
PASSWORD = Config.PASSWORD
DEVICE_ID = Config.DEVICE_ID

class MainHandler(webapp.RequestHandler):
    def get(self):   
        path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
        self.response.out.write(template.render(path, {}))


class LEDimHandler(webapp.RequestHandler):
    def get(self):
        chan = self.request.get('chan')
        channel_name = "xbib0.led1"
        q = Sample.gql("WHERE channel_name = :1 "
                        "ORDER BY timestamp DESC "
                        "LIMIT 1", channel_name)
        row = q.get()
        
        str_value = ""
        str_value = str(row.value)
        if str_value == "OFF":
            onoff = "ON"
            n = "1"
        elif str_value == "ON":
            onoff = "OFF"
            n = "2"
        else: 
            self.error('403')    
        template_values = {
            'name': channel_name,
            'percent': n,
            'label': chan
        }
        sample = Sample(channel_name, value = onoff)
        idigi_client = iDigiClient(username=USERNAME, password=PASSWORD)
        idigi_client.channel_set(device_id=DEVICE_ID, sample=sample)        
        path = os.path.join(os.path.dirname(__file__), 'templates/led.html')
        self.response.out.write(template.render(path, template_values))
        
        
class LEDupHandler(webapp.RequestHandler):
    def get(self):
        chan = self.request.get('chan')
        channel_name = "xbib0.led" + chan
        q = Sample.gql("WHERE channel_name = :1 "
                        "ORDER BY timestamp DESC "
                        "LIMIT 1", channel_name)
        row = q.get()
        
        str_value = "" 
        str_value = str(row.value)    
        template_values = {
            'name': channel_name,
            'label': str_value
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/led.html')
        self.response.out.write(template.render(path, template_values))


class LEDHandler(webapp.RequestHandler):
    def get(self):
        chan = self.request.get('chan')
        onoff = self.request.get('onoff').lower().capitalize()
        if onoff not in ('On', 'Off'):
            self.error('403') 
        sample = Sample(channel_name = "xbib0.led" + chan, value = onoff)
        idigi_client = iDigiClient(username=USERNAME, password=PASSWORD)
        idigi_client.channel_set(device_id=DEVICE_ID, sample=sample)        


class GaugeHandler(webapp.RequestHandler):
    SOURCE_MAP = {
    }
    VALUE_XFORM_MAP = {
    }
    PCT_XFORM_MAP = {
        'xbr0.light': lambda x: x/300.0*100,
		'xbr1.light': lambda x: x/300.0*100,
		'sensor0.light': lambda x: x/300.0*100,
        'xbr0.temperature': lambda x: x/40.0*100,
		'xbr1.temperature': lambda x: x/40.0*100,
		'sensor0.temperature': lambda x: x/40.0*100,
        'xbib0.led1': lambda x: x*1,
		'xbib0.led2': lambda x: x*1,
        'xbib0.led3': lambda x: x*1,
    }
    UNIT_MAP = {
        'xbr0.light': 'Brightness',
		'xbr1.light': 'Brightness',
		'sensor0.light': 'Brightness',
        'xbr0.temperature': 'C',
		'xbr1.temperature': 'C',
		'sensor0.temperature': 'C',
		'xbib0.led1': 'Status',
		'xbib0.led2': 'Status',
		'xbib0.led2': 'Status'
    }
    COLOR_MAP = {
        'xbr0.light': ('FFFFFF','DDDD33'),
		'xbr1.light': ('FFFFFF','DDDD33'),
		'sensor0.light': ('FFFFFF','DDDD33'),
        'xbr0.temperature': ('0000FF','FF0000'),
		'xbr1.temperature': ('0000FF','FF0000'),
		'sensor0.temperature': ('0000FF','FF0000'),
        'xbib0.led1': ('FFFFFF','FFFF00'),
		'xbib0.led2': ('FFFFFF','FFFF00'),
		'xbib0.led3': ('FFFFFF','FFFF00'),
    }
    LABEL_MAP = {
        'xbr0.light': "Light",
		'xbr1.light': "Light2",
		'sensor0.light': "Light3",
        'xbr0.temperature': "Temperature",
		'xbr1.temperature': "Temperature2",
		'sensor0.temperature': "Temperature3",
        'xbib0.led1': "LED1",
		'xbib0.led2': "LED2",
		'xbib0.led3': "LED3",
    }
    def get(self):
        gauge = self.request.get('name')

        channel_name = gauge
        if channel_name in GaugeHandler.SOURCE_MAP:
            channel_name = GaugeHandler.SOURCE_MAP[channel_name]

        q = Sample.gql("WHERE channel_name = :1 "
                        "ORDER BY timestamp DESC "
                        "LIMIT 1", channel_name)
        row = q.get()
        
        value = 0.0
        unit = "undef"
        percent = 0.0
        
        
        
        if row:
          unit = row.unit
          if unit=="C" or unit=="brightness":
            value = float(row.value)
            if unit=="brightness":
                if channel_name == "xbr0.light":
                    l_num = "1"
                elif channel_name == "xbr1.light":
                    l_num = "2"
                elif channel_name == "sensor0.light":
                    l_num = "3"
                if value < 50:
                    nff="ON"
                else:
                    nff="OFF"
                sample = Sample(channel_name = "xbib0.led" + l_num, value = nff)
                idigi_client = iDigiClient(username=USERNAME, password=PASSWORD)
                idigi_client.channel_set(device_id=DEVICE_ID, sample=sample)
            if gauge in GaugeHandler.VALUE_XFORM_MAP:
              value = GaugeHandler.VALUE_XFORM_MAP[gauge](value)
            if value < 0.2:
              value = 0.0
            percent = value
            if gauge in GaugeHandler.PCT_XFORM_MAP:
              percent = GaugeHandler.PCT_XFORM_MAP[gauge](value)
            if gauge in GaugeHandler.UNIT_MAP:
              unit = GaugeHandler.UNIT_MAP[gauge]
              
          elif unit=="":
            str_value = str(row.value)
            if gauge in GaugeHandler.PCT_XFORM_MAP:
              percent = GaugeHandler.PCT_XFORM_MAP[gauge](value)
              if str_value == "Off":
                percent = 0
                value = 0
              elif str_value == "On":
                percent = 100
                value = 1
            if gauge in GaugeHandler.UNIT_MAP:
              unit = GaugeHandler.UNIT_MAP[gauge]
        
        template_values = {
            'name': gauge,
            'percent': urllib.quote_plus("%.1f" % percent),
            'data_label': urllib.quote_plus("%.1f %s" % (value, unit)),
            'color_start': GaugeHandler.COLOR_MAP[gauge][0],
            'color_end': GaugeHandler.COLOR_MAP[gauge][1],
            'label': GaugeHandler.LABEL_MAP[gauge], 
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/gauge.html')
        self.response.out.write(template.render(path, template_values))
        
    
def main():
  logging.getLogger().setLevel(logging.DEBUG)
  application = webapp.WSGIApplication(
                    [
                        ('/', MainHandler),
                        ('/gauge', GaugeHandler),
                        ('/led', LEDHandler),
                        ('/ledim', LEDimHandler),
                        ('/upled', LEDupHandler),
                    ],
                    debug=True)
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
